package logic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class Template implements Serializable, Presentable{
	private final class RowIterator implements
			Iterator<Row> {
		Iterator<List<TemplateEntry>>  i = teLists.iterator();
		
		public boolean hasNext() {
			return i.hasNext();
		}

		public Row next() {
			return new TemplateRow(i.next());
		}

		public void remove() {
			i.remove();

			
		}
	}

	transient private String templateCode;
	private static final long serialVersionUID = 10001L;
	private String header;
	private int lastEntryId = 0;
	
	
	private final List <List<TemplateEntry> > teLists = new ArrayList<List<TemplateEntry>>();
	
	public void reset() {
		teLists.clear();
	}
	
	public void setHeader(String header) {
		this.header = header;
	}
	public String getHeader() {
		return header;
	}
	public Iterator<Row> iterator(){
		return new RowIterator();
		
	} 
	
	public class TemplateRow implements Row{
		
		private final List<TemplateEntry> list;
		
		TemplateRow (List <TemplateEntry> list){
			this.list = list;
		}

		public Iterator<? extends Entry> iterator() {
			return list.iterator();
		}
		@Override
		public Entry createEntry() {
			TemplateEntry entry = new TemplateEntry(this);
			entry.setId(++lastEntryId);
			list.add(entry);
			return entry;
		}
		@Override
		public void removeFromParent() {
			teLists.remove(list);
		}
		public void removeEnrty(Entry e){
			list.remove(e);
		}

		public void addEntry(Entry e) {
			
			TemplateEntry templateEntry = (TemplateEntry) e;
			if (templateEntry.getId() <= 0)
				templateEntry.setId(++lastEntryId);
			list.add(templateEntry);

		}
		
	}

	public Row createRow() {
		ArrayList<TemplateEntry> list = new ArrayList<TemplateEntry> ();
		teLists.add(list);
		return new TemplateRow(list);
	} 

	public TemplateEntry getById(int id) {
		for (List<TemplateEntry> ll : teLists) {
			for (TemplateEntry templateEntry : ll) {
				if (templateEntry.getId() == id)
					return templateEntry;
			}
		}
		return null;
	}

	public Vector<TemplateEntry> allEntries() {
		Vector<TemplateEntry> vector = new Vector<TemplateEntry>();
		for (List<TemplateEntry> ll : teLists) {
			vector.addAll(ll);
		}
		return vector;
	}

	public void setTemplateCode(String templateCode) {
		this.templateCode = templateCode;
	}

	public String getTemplateCode() {
		return templateCode;
	}


}
